//
//  ViewController.m
//  SKU
//
//  Created by lingji001 on 2018/7/24.
//  Copyright © 2018年 lingji001. All rights reserved.
//

#import "ViewController.h"
#import <FirstProjects/PublicHead.h>
#import "Model.h"
#import "ZHCollectionViewCell.h"
#import "ZHCollectionReusableView.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (strong, nonatomic)  UICollectionView *collectionView;
@property (nonatomic, strong) Model *model;

/**
 已选数组
 */
@property (nonatomic, strong) NSMutableArray <NSString *>*selArray;

/**
 可选数组
 */
@property (nonatomic, strong) NSMutableArray <NSString *>*opSelArray;



@end

@implementation ViewController


/**
    数据处理
        1. 假设有一个 ’特性‘ ，在Z中不存在，那么移除这个 ’特性‘
 */

/**
    SKU 逻辑处理
 
    商品可能有 N 种属性
    每一个属性 可能有 M 个 ‘特性‘
    有 Z 个可选库存
 
    假设选择其中一个 ‘特性’
 
    首先判断出这个 ‘特性’ 属于哪个属性
1.    然后判断出当前属性下的所有 ‘特性’ 是否都存在于 Z 中                  --------------        方法分离 ， 此方法只在选择一个时用到
    如果 存在
    添加进入可选数组
2.    然后判断 Z 中所有包含这个 ‘特性’ 的所有 ‘特性’
    将包含的 ’特性‘ 加入可选数组
 
    假设选择了多个
3.    首先判断是不是所有的 属性 都被选择到了
        如果不是
        判断满足以上选择所有 ’特性‘ 的剩余 特性有哪些
        添加进入可选数组
 
 4.     进入最后一步收网
        当已选属性大于 1 时
        逐一移除当前已选属性
        看看满足其他已选属性时，当前分组还有哪些 ’特性‘ 可选
        将满足的 ’特性‘ 添加进入 ’可选数组‘
 
 
 */


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self configUI];
    self.selArray = [NSMutableArray array];
    self.opSelArray = [NSMutableArray array];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"File" ofType:nil];
    NSData *jsonData = [NSData dataWithContentsOfFile:path];
    NSError *err;
    NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    self.model = [Model modelWithDictionary:dic];
    
    ////////////////////////////////把不能选的属性筛出去////////////////////////////////////////////
    NSMutableArray *array = [NSMutableArray array];
    for (SkuCodes *model in self.model.data.skuCodes) {
        for (NSString *string1 in [model.skuAttr componentsSeparatedByString:@","]) {
            [array addObject:[string1 componentsSeparatedByString:@":"].lastObject];
        }
    }
    for (SellAttrs *model in self.model.data.sellAttrs) {
        NSMutableArray *array1 = [NSMutableArray array];
        for (AttrValues *model1 in model.attrValues) {
            if ([array containsObject:@(model1.valueId).stringValue]) {
                [array1 addObject:model1];
            }
            if (model1.checked == YES) {
                [self.selArray addObject:model1.valueName];
            }
        }
        model.attrValues = array1;
    }
    [self loadOptionalArray];
    ////////////////////////////////////////////////////////////////////////////
//    _model;
    NSLog(@"%@",dic);
}
////////////////////////////////////////////////逻辑处理//////////////////////////////////////////////////////////////////////

#pragma mark 开始向可选数组中添加元素
- (void)loadOptionalArray{
    NSMutableArray *oplArray = [NSMutableArray array];
    [oplArray addObjectsFromArray:[self searchNameArrayWithZ:[self searchZWithArray:self.selArray]]];
    if (self.selArray.count == 1) {
        [oplArray addObjectsFromArray:[self searchNameArrayWithSellAttrs:[self searchSellAttrsWithName:self.selArray.firstObject]]];
    }
    for (NSString *string in self.selArray) {
        NSMutableArray <NSString *>*array = [NSMutableArray arrayWithArray:self.selArray];
        if (array.count > 1) {
            [array removeObject:string];
            NSArray <NSString *>*array1 = [self searchNameArrayWithZ:[self searchZWithArray:array]];
            for (NSString *string1 in [self searchNameArrayWithSellAttrs:[self searchSellAttrsWithName:string]]) {
                if ([array1 containsObject:string1]) {
                    [oplArray addObject:string1];
                }
            }
        }
    }
    self.opSelArray = [self heavyArray:oplArray];
}

#pragma mark 通过 ‘特性’ name 查找对应的 ‘id’
- (NSString *)searchIdWithName:(NSString *)name{
    NSString *nameid = @"";
    for (SellAttrs *model1 in self.model.data.sellAttrs) {
        for (AttrValues *model2 in model1.attrValues) {
            if ([model2.valueName isEqualToString:name]) {
                nameid = @(model2.valueId).stringValue;
                break;
            }
        }
        if (nameid.length > 0) {
            break;
        }
    }
    return nameid;
}

#pragma mark 通过 ‘特性’ name 查找对应的 ‘属性’
- (SellAttrs *)searchSellAttrsWithName:(NSString *)name{
    SellAttrs *model = nil;
    for (SellAttrs *model1 in self.model.data.sellAttrs) {
        for (AttrValues *model2 in model1.attrValues) {
            if ([model2.valueName isEqualToString:name]) {
                model = model1;
                break;
            }
        }
        if (model) {
            break;
        }
    }
    return model;
}

#pragma mark 查找当前 ‘属性’ 的所有 ‘特性’ 的 id
- (NSArray <NSString *>*)searchIdWithSellAttrs:(SellAttrs *)model{
    NSMutableArray <NSString *>*array = [NSMutableArray array];
    for (AttrValues *model1 in model.attrValues) {
        [array addObject:@(model1.valueId).stringValue];
    }
    return [NSArray arrayWithArray:array];
}

#pragma mark 查找当前 ‘属性’ 的所有 ‘特性’ 的 name
- (NSArray <NSString *>*)searchNameArrayWithSellAttrs:(SellAttrs *)model{
    NSMutableArray <NSString *>*array = [NSMutableArray array];
    for (AttrValues *model1 in model.attrValues) {
        [array addObject:model1.valueName];
    }
    return [NSArray arrayWithArray:array];
}

#pragma mark 传入 ‘特性’ 数组，返回 ‘Z’ 库中满足条件的 'id' 数组
- (NSArray <NSString *>*)searchZWithArray:(NSArray <NSString *>*)array{
    NSMutableArray <NSString *>*array1 = [NSMutableArray array];
    for (SkuCodes *model in self.model.data.skuCodes) {
        int flag = 0;
        for (NSString *string in array) {
            if (![self fatherString:model.skuAttr son:[self searchIdWithName:string]]) {
                flag = 1;
            }
        }
        if (flag == 0) {
            [array1 addObject:model.skuAttr];
        }
    }
    return [NSArray arrayWithArray:array1];
}

#pragma mark 判断 当前字符串 是否包含另一个字符串
- (BOOL)fatherString:(NSString *)father son:(NSString *)son{
    return [father rangeOfString:son].location != NSNotFound;
}

#pragma mark 通过 ‘特性’ id 查找对应 ‘name’
- (NSString *)searchNameWithId:(NSString *)Id{
    NSString *nameid = @"";
    for (SellAttrs *model1 in self.model.data.sellAttrs) {
        for (AttrValues *model2 in model1.attrValues) {
            if ([@(model2.valueId).stringValue isEqualToString:Id]) {
                nameid = @(model2.valueId).stringValue;
                break;
            }
        }
        if (nameid.length > 0) {
            break;
        }
    }
    return nameid;
}

#pragma mark 数组去重
- (NSMutableArray *)heavyArray:(NSArray *)array{
    NSMutableArray *array1 = [NSMutableArray array];
    for (id objcet in array) {
        if (![array1 containsObject:objcet]) {
            [array1 addObject:objcet];
        }
    }
    return array1;
}

#pragma mark 把满足 筛选后 的 ‘Z’ 库中所有对应的 ‘特性’ name 找出来
- (NSArray <NSString *>*)searchNameArrayWithZ:(NSArray <NSString *>*)zArray{
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *z in zArray) {
        for (NSString *attid in [z componentsSeparatedByString:@","]) {
            NSString *attid1 = [attid componentsSeparatedByString:@":"].firstObject;
            NSString *valueid = [attid componentsSeparatedByString:@":"].lastObject;
            for (SellAttrs *moedl in self.model.data.sellAttrs) {
                if ([@(moedl.attrId).stringValue isEqualToString:attid1]) {
                    for (AttrValues *model1 in moedl.attrValues) {
                        if ([@(model1.valueId).stringValue isEqualToString:valueid]) {
                            [array addObject:model1.valueName];
                        }
                    }
                }
            }
        }
    }
    return [NSArray arrayWithArray:array];
}

#pragma mark 当前选择的name
- (void)selectName:(NSString *)name{
    NSMutableArray *selArray = [NSMutableArray arrayWithObject:name];
    NSMutableArray *selArray2 = [NSMutableArray arrayWithArray:self.selArray];
    for (NSString *string in [self searchNameArrayWithSellAttrs:[self searchSellAttrsWithName:name]]) {
        if ([selArray2 containsObject:string]) {
            [selArray2 removeObject:string];
        }
    }
    for (NSString *string in selArray2) {
        [selArray addObject:string];
        if ([self searchNameArrayWithZ:[self searchZWithArray:selArray]].count == 0) {
            [selArray removeObject:string];
        }
    }
    self.selArray = [self heavyArray:selArray];
    [self loadOptionalArray];
}

///////////////////////////////////////////下面是UI部分//////////////////////////////////////////////////////////////

#pragma mark 初始化UI控件
- (void)initUI{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[ZHCollectionViewCell class] forCellWithReuseIdentifier:ZHCollectionViewCellId];
    [self.collectionView registerClass:[ZHCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ZHCollectionReusableViewId];
}

#pragma mark 为UI控件添加约束
- (void)configUI{
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.equalTo(self.mas_topLayoutGuide);
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.model.data.sellAttrs.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.model.data.sellAttrs[section].attrValues.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZHCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ZHCollectionViewCellId forIndexPath:indexPath];
    cell.model = self.model.data.sellAttrs[indexPath.section].attrValues[indexPath.row];
    cell.layer.borderWidth = 1;
    if ([self.selArray containsObject:cell.model.valueName]) {//已选
        cell.layer.borderColor = [UIColor redColor].CGColor;
    }else if ([self.opSelArray containsObject:cell.model.valueName]) {//可选
        cell.layer.borderColor = [UIColor blackColor].CGColor;
    }else{//不可选
        cell.layer.borderColor = [UIColor greenColor].CGColor;
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(100, 40);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        ZHCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:ZHCollectionReusableViewId forIndexPath:indexPath];
        view.contentLabel.text = self.model.data.sellAttrs[indexPath.section].attrName;
        view.layer.borderColor = [UIColor blackColor].CGColor;
        view.layer.borderWidth = 1;
        return view;
    }else{
        return nil;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.view.bounds.size.width - 20, 50);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ZHCollectionViewCell *cell = (ZHCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    [self selectName:cell.model.valueName];
    [collectionView reloadData];
}

@end
